const User = require('../model/users')
const jsonwebtoken = require('jsonwebtoken')
const { secret } = require('../config')
const Question = require('../model/questions')
const Answer = require('../model/answer')

class UsersCtl {
  // 鉴权中间件
  async checkOwner(ctx, next) {
    if (ctx.params.id !== ctx.state.user._id) {
      ctx.throw(403, "没有权限")
    }
    await next()
  }
// 检查用户是否存在
  async checkUserExist(ctx, next) {
    const user = await User.findById(ctx.params.id)
    if(!user) {
      ctx.throw(404, "用户不存在")
    }
    await next()
  }

  async find(ctx) {
    const { per_page = 10, page = 1} =ctx.query 
    const perpage = Math.max(per_page * 1 , 1)
    const pages = Math.max(page * 1, 1) -1
    ctx.body = await User.find({ name: new RegExp(ctx.query.q)}).limit(perpage).skip(pages*perpage)
  }

  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const populateStr = fields.split(';').filter(f => f).map(f => {
      if(f === 'educations'){
        return 'educations.school educations.major'
      }
      if(f === 'employments') {
        return 'employments.company employments.job'
      }
      return f
    }).join(' ')
    const user = await User.findById(ctx.params.id).select(selectFields).populate(populateStr)
    if (!user) {
      ctx.throw(404, "用户不存在")
    }
    ctx.body = user
  }

  async create(ctx) {
    ctx.verifyParams({
      name: {
        type: 'string',
        required: true
      },
      password: {
        type: 'string',
        required: true
      }
    })
    const { name } = ctx.request.body
    const repeatedUser = await User.findOne({ name })
    if (repeatedUser) {
      ctx.throw(409, "用户存在")
    }
    const user = await new User(ctx.request.body).save()
    ctx.body = {
      name: user.name,
      id: user._id
    }
  }

  async update(ctx) {
    ctx.verifyParams({
      name: {
        type: 'string',
        required: false
      },
      password: {
        type: 'string',
        required: false
      },
      avatar_url: { type: 'string', required: false },
      gender: { type: 'string', required: false },
      headline: { type: 'string', required: false },
      locations: { type: 'array', itemType: 'string', required: false },
      business: { type: 'string', required: false },
      employments: { type: 'array', itemType: 'object', required: false },
      educations: { type: 'array', itemType: 'object', required: false },
    })
    const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    if (!user) {
      ctx.throw(404, '用户不存在')
    }
    ctx.body = {
      name: user.name,
      id: user._id
    }
  }

  async del(ctx) {
    const user = await User.findByIdAndRemove(ctx.params.id)
    if (!user) {
      ctx.throw(404, '用户不存在')
    }
    ctx.status = 204
  }


  async login(ctx) {
    ctx.verifyParams({
      name: {
        type: 'string',
        required: true
      },
      password: {
        type: 'string',
        required: true
      }
    })
    const user = await User.findOne(ctx.request.body)
    if (!user) {
      ctx.throw(401, "用户名密码不正确")
    }
    const { _id, name } = user
    const token = jsonwebtoken.sign({ _id, name }, secret, {
      expiresIn: '1d'
    })
    ctx.body = {
      token,
      message: '登陆成功',
      status: 200
    }
  }





// 关注和粉丝部分代码




//关注某人
async follow(ctx) {
  const me = await User.findById(ctx.state.user._id).select('+following');
  if(!me.following.map(id => id.toString()).includes(ctx.params.id)) {
    me.following.push(ctx.params.id)
    me.save()
  }
  ctx.status = 204
}

// 取消关注某人
async unfollow(ctx) {
  const me = await User.findById(ctx.state.user._id).select('+following');
  const index = me.following.map(id => id.toString()).indexOf(ctx.params.id)
  if(index > -1 ) {
    me.following.splice(index,1)
    me.save()
  }
  ctx.status = 204
}
// 获取关注列表
  async listFollowing(ctx) {
    const user = await User.findById(ctx.params.id).select("+following").populate('following')
    if(!user) {
      ctx.throw(404,"未查到该用户啊！")
    }
    ctx.body = user.following
  }


  // 获取粉丝列表
  async listFollower(ctx) {
    const user = await User.find({following: ctx.params.id})
    ctx.body = user
  }



// 话题部分


// 关注话题
  async followTopic(ctx) {
    const me = await User.findById(ctx.state.user._id).select('+followingTopic');
    if(!me.followingTopic.map(id => id.toString()).includes(ctx.params.id)) {
      me.followingTopic.push(ctx.params.id)
      me.save()
    }
    ctx.status = 204
  }
  // 取消关注话题
  async unfollowTopic(ctx) {
    const me = await User.findById(ctx.state.user._id).select('+followingTopic');
    const index = me.followingTopic.map(id => id.toString()).indexOf(ctx.params.id)
    if(index > -1 ) {
      me.followingTopic.splice(index,1)
      me.save()
    }
    ctx.status = 204
  }

  async listFollowingTopic(ctx) {
    const user = await User.findById(ctx.params.id).select("+followingTopic").populate('followingTopic')
    if(!user) {
      ctx.throw(404,"未查到该用户啊！")
    }
    ctx.body = user.followingTopic
  }
// 用户创建问题列表
  async listQuestion (ctx) {
    const questions = await Question.find({ questioner: ctx.params.id })
    ctx.body  = questions
  }












// 用户关注问题列表
  async followQuestion(ctx) {
    const me = await User.findById(ctx.state.user._id).select('+followingQuestion');
    if(!me.followingQuestion.map(id => id.toString()).includes(ctx.params.id)) {
      me.followingQuestion.push(ctx.params.id)
      me.save()
    }
    ctx.status = 204
  }
  // 取消关注问题
  async unfollowQuestion(ctx) {
    const me = await User.findById(ctx.state.user._id).select('+followingQuestion');
    const index = me.followingQuestion.map(id => id.toString()).indexOf(ctx.params.id)
    if(index > -1 ) {
      me.followingQuestion.splice(index,1)
      me.save()
    }
    ctx.status = 204
  }

  //用户关注问题列表
  async listFollowingQuestion(ctx) {
    const user = await User.findById(ctx.params.id).select("+followingQuestion").populate('followingQuestion')
    if(!user) {
      ctx.throw(404,"未查到该用户啊！")
    }
    ctx.body = user.followingQuestion
  }




// 用户点赞
async followAnswer(ctx, next) {
  const me = await User.findById(ctx.state.user._id).select('+likingAnswer');
  
  if(!me.likingAnswer.map(id => id.toString()).includes(ctx.params.id)) {
    me.likingAnswer.push(ctx.params.id)
    me.save()
    const a = await Answer.findByIdAndUpdate(ctx.params.id, { $inc: { voterCount: 1}})
    console.log(a)
  }
  ctx.status = 204
  
  await next()
}
// 取消点赞
async unfollowAnswer(ctx) {
  const me = await User.findById(ctx.state.user._id).select('+likingAnswer');
  const index = me.likingAnswer.map(id => id.toString()).indexOf(ctx.params.id)
  if(index > -1 ) {
    me.likingAnswer.splice(index,1)
    me.save()
    if(Answer.findById(ctx.params.id).voterCount > 0){
      await Answer.findByIdAndUpdate(ctx.params.id, { $inc: { voterCount: -1}})
    }
  }
  ctx.status = 204
}
//喜欢答案列表
async listLikingAnswer(ctx) {
  const user = await User.findById(ctx.params.id).select("+likingAnswer").populate('likingAnswer')
  if(!user) {
    ctx.throw(404,"未查到该用户啊！")
  }
  ctx.body = user.likingAnswer
}

// 踩


async disfollowAnswer(ctx, next) {
  const me = await User.findById(ctx.state.user._id).select('+dislikingAnswer');
  if(!me.dislikingAnswer.map(id => id.toString()).includes(ctx.params.id)) {
    me.dislikingAnswer.push(ctx.params.id)
    me.save()
  }
  ctx.status = 204
  await next()
}
// 取消cai
async undisfollowAnswer(ctx) {
  const me = await User.findById(ctx.state.user._id).select('+dislikingAnswer');
  const index = me.dislikingAnswer.map(id => id.toString()).indexOf(ctx.params.id)
  if(index > -1 ) {
    me.dislikingAnswer.splice(index,1)
    me.save()
  }
  ctx.status = 204
}
//cai答案列表
async dislistLikingAnswer(ctx) {
  const user = await User.findById(ctx.params.id).select("+dislikingAnswer").populate('dislikingAnswer')
  if(!user) {
    ctx.throw(404,"未查到该用户啊！")
  }
  ctx.body = user.dislikingAnswer
}










// 收藏答案


async collectAnswer(ctx, next) {
  const me = await User.findById(ctx.state.user._id).select('+collectAnswer');
  if(!me.collectAnswer.map(id => id.toString()).includes(ctx.params.id)) {
    me.collectAnswer.push(ctx.params.id)
    me.save()
  }
  ctx.status = 204
  await next()
}
// 取消cai
async uncollectAnswer(ctx) {
  const me = await User.findById(ctx.state.user._id).select('+collectAnswer');
  const index = me.collectAnswer.map(id => id.toString()).indexOf(ctx.params.id)
  if(index > -1 ) {
    me.collectAnswer.splice(index,1)
    me.save()
  }
  ctx.status = 204
}
//cai答案列表
async listCollectAnswer(ctx) {
  const user = await User.findById(ctx.params.id).select("+collectAnswer").populate('collectAnswer')
  if(!user) {
    ctx.throw(404,"未查到该用户啊！")
  }
  ctx.body = user.collectAnswer
}

}
module.exports = new UsersCtl()